<template>
  <div ref="editorContainer" class="editor-container"></div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount } from "vue";
import loader from "@monaco-editor/loader";
const props = defineProps({
  content: {
    type: String,
    default: "1",
  },
  //语言
  language: {
    type: String,
    default: "javascript",
  },
  //主题
  theme: {
    type: String,
    default: "vs-dark",
  },
  // 是否启用预览图
  minimap: {
    type: Boolean,
    required: true,
  },
  //设置为只读模式
  readOnly: {
    type: Boolean,
    default: true,
  },
});

const editorContainer = ref();
let editor;
let model;

onMounted(() => {
  loader.init().then((monaco) => {
    let { content, language, theme, minimap, readOnly } = props;
    // 创建一个新的模型
    model = monaco.editor.createModel(content, language || "vue");
    // 创建编辑器并绑定模型
    editor = monaco.editor.create(editorContainer.value, {
      model: model,
      theme,
      minimap,
      // 圆角
      roundedSelection: true,
      // 主键
      multiCursorModifier: "ctrlCmd",
      // 滚动条
      scrollbar: {
        verticalScrollbarSize: 8,
        horizontalScrollbarSize: 8,
      },
      // 行号
      lineNumbers: "off",
      // tab大小
      tabSize: 2,
      //字体大小
      fontSize: 16,
      // 控制编辑器在用户键入、粘贴、移动或缩进行时是否应自动调整缩进
      autoIndent: "advanced",
      // 自动布局
      automaticLayout: true,
      readOnly,
    });
    // 监听模型内容变化
    model.onDidChangeContent(() => {
      //   console.log("内容已更改:", model.getValue());
    });
  });
});

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose();
  }
  if (model) {
    model.dispose();
  }
});
</script>
<style scoped>
.editor-container {
  width: 100%;
  height: 100%;
}
</style>
